const {
  MemberModel
} = require('../../utils/member-model.js')
const memberModel = new MemberModel()
const app = getApp()
Page({
  data: {
    operatorId: '',
    shareChannel: '',
    source: '',
    shopId: ''
  },
  onLoad: function (options) {
    this.setData({
      operatorId: options.operatorId,
      shareChannel: options.shareChannel,
      source: options.source,
      shopId: options.shopId
    })
    app.globalData.isShare = true
  },
  getUserInfo({ detail }) {
    const { encryptedData, iv } = detail
    if (encryptedData) {
      memberModel.registerActivity({
        merchantId: wx.getStorageSync('merchantId')
      }).then(data => {
        if (data) {
          if (data.channel === '*' || data.channel.includes('0')) {
            const gifts = data.activityGiftList.map(item => {
              return {
                ...item,
                couponType: item.refType,
                couponName: item.refName
              }
            })
            const shareData = {
              operatorId: this.data.operatorId,
              source: this.data.source,
              shareChannel: this.data.shareChannel,
              shopId: this.data.shopId
            }
            wx.setStorageSync('shareData', shareData)
            wx.redirectTo({
              url: `/pages/index/index?registerGifts=${JSON.stringify(gifts)}&giftNeedLogin=${1}&encryptedData=${encryptedData}&iv=${iv}`,
            })
          } else {
            this.goLogin()
          }
        } else {
          this.goLogin()
        }
      })
    }
  },
  goLogin() {
    const shareData = {
      operatorId: this.data.operatorId,
      source: this.data.source,
      shareChannel: this.data.shareChannel,
      shopId: this.data.shopId
    }
    wx.setStorageSync('shareData', shareData)
    wx.redirectTo({
      url: `/pages/login/index?shareData=${JSON.stringify(shareData)}`,
    })
  }
})